package com.ssh.cp.aop;

import java.util.Date;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ssh.cp.entity.LoginLog;
import com.ssh.cp.entity.User;
import com.ssh.cp.idao.ILogDao;
@Component  
@Aspect 
public class LoginLogger{
	@Autowired
	ILogDao logDao;
	
	@Pointcut("execution(* com.ssh.cp.service.UserService.login(*))")
	public void log() {
		// TODO Auto-generated method stub
		System.out.println("*************Log*******************");
	}
	
	
	@Before("log()")    
	public void beforeAdvice() {    
	    System.out.println("===========before advice==============");    
	}
	@After(value = "log()")
	public void afterAdvice() {    
	    System.out.println("===========这是后置通知 ==============");    
	}
	
	@Around("log()")
    public Object monitorAround(ProceedingJoinPoint jp) throws Throwable {

        System.out.println("method start time:" + System.currentTimeMillis());
        Object[] arg=jp.getArgs();
        
        Object re = jp.proceed(arg);

        
        
        List<?> l=(List<?>)re;
        LoginLog loginlog=new LoginLog();
		User u;
		if(!l.isEmpty()) {
			u=(User)l.get(0);
			loginlog.setUserid(u.getUserid());
			loginlog.setUsername(u.getUsername());
			loginlog.setDescription(u.getUsername()+"成功登录了系统。");
			loginlog.setTime(new Date(System.currentTimeMillis()));
			System.out.println("************"+loginlog.getDescription()+"***********");
			logDao.addLoginLog(loginlog);
			
		}
		System.out.println("method end time:" + new Date(System.currentTimeMillis()));
        return re;
    }
	
	
	@AfterReturning(value = "log()",  returning="rvt")  
	public void myAfterReturnAdvice(Object rvt) { 
		List<?> l=(List<?>)rvt;
		User u;
		if(!l.isEmpty()) {
			u=(User)l.get(0);
		 System.out.println("+++++++++++++++这是后置通知 ++++++++++++++++++" + " result: " +u.getUsername()+"登录成功！"); 
		}else {
			 System.out.println("+++++++++++++++这是后置通知 ++++++++++++++++++" + " result: 登录失败！");
		}
	}  
}
